/*
	Copyright (c) 2007, ANYwebcam.com Pty Ltd. All rights reserved.

	The software in this package is published under the terms of the BSD style 
	license, a copy of which has been included with this distribution in the 
	license.txt file.
*/
package com.anywebcam.di.util
{
	import com.anywebcam.di.DIContainer;

	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	
	// todo: list events this Class dispatches

	public class ComponentDefinitionsLoader extends EventDispatcher
	{
		public function ComponentDefinitionsLoader( container:DIContainer, parser:ComponentDefinitionsParser, request:URLRequest = null )
		{
			super();
			
			_container = container;

			_parser = parser;
			_parser.addEventListener( Event.COMPLETE, parser_complete );
			_parser.addEventListener( IOErrorEvent.IO_ERROR, parser_ioError );
			
			_loader = new URLLoader();
			_loader.dataFormat = URLLoaderDataFormat.TEXT;
			_loader.addEventListener( Event.COMPLETE, loader_complete );
			_loader.addEventListener( IOErrorEvent.IO_ERROR, loader_ioError );
			_loader.addEventListener( SecurityErrorEvent.SECURITY_ERROR, loader_securityError );
			
			if( request ) load( request );
		}
		
		private var _container:DIContainer;

		public function get container():DIContainer
		{
			return _container;
		}

		public function set container( value:DIContainer ):void
		{
			_container = value;
		}
		
		
		private var _parser:ComponentDefinitionsParser;

		public function get parser():ComponentDefinitionsParser
		{
			return _parser;
		}

		public function set parser( value:ComponentDefinitionsParser ):void
		{
			_parser = value;
		}		
		
		private var _loader:URLLoader;

		public function get loader():URLLoader
		{
			return _loader;
		}

		public function set loader( value:URLLoader ):void
		{
			_loader = value;
		}

		public function load( request:URLRequest ):void
		{
			_loader.load( request );
		}
		
		protected function parser_complete( event:Event ):void
		{
			dispatchEvent( event );			
		}
		
		protected function parser_ioError( event:Event ):void
		{
			trace( this, 'parser_ioError', event );

			dispatchEvent( event );
		}
				
		protected function loader_complete( event:Event ):void
		{
			parser.parse( container, loader.data );
		}
		
		protected function loader_ioError( event:IOErrorEvent ):void
		{
			trace( this, 'loader_ioError', event );
		
			dispatchEvent( event );
		}
		
		protected function loader_securityError( event:SecurityErrorEvent ):void
		{
			trace( this, 'loader_securityError', event );

			dispatchEvent( event );
		}
	}
}